package stream

import (
	"encoding/json"
	"github.com/prometheus/prometheus/prompb"
	"gluenet/pkg/apis"
	"strings"
	"sync"
)

func metrics(c *apis.StorageContext, tms *prompb.TimeSeries) {
	var kv = make(map[string]string, len(tms.Labels))
	for _, label := range tms.Labels {
		kv[label.Name] = label.Value
	}

	//c.Logger.Debugf("kv: %v\n", kv)

	data := map[string]interface{}{
		"object":   kv["object"],
		"platform": kv["platform"],
		"value":    tms.Samples[0].Value,
		"time":     tms.Samples[0].Timestamp / 1000,
	}

	var key string
	switch kv["platform"] {
	case "kubernetes":
		switch kv["object"] {
		case "machine":
			key = strings.Join([]string{kv["platform"], kv["label"], kv["agent_guid"], kv["host_name"]}, "|")
			data["label"] = kv["label"]
			data["guid"] = kv["application_guid"]
			data["node"] = kv["instance"]
		case "application":
			key = strings.Join([]string{kv["platform"], kv["label"], kv["application_guid"], kv["container"]}, "|")
			data["label"] = kv["label"]
			data["guid"] = kv["application_guid"]
			data["container"] = kv["container"]
		}
	case "gluenets":
		switch kv["object"] {
		case "machine":
			key = strings.Join([]string{kv["platform"], kv["label"], kv["agent_guid"], kv["host_name"]}, "|")
			data["label"] = kv["label"]
			data["guid"] = kv["agent_guid"]
			data["node"] = kv["host_name"]
		case "application":
			//cts := strings.Split(kv["container"], "_")
			key = strings.Join([]string{kv["platform"], kv["label"], kv["application_guid"], kv["container"]}, "|")
			data["label"] = kv["label"]
			data["guid"] = kv["application_guid"]
			data["container"] = kv["container"]
			c.MetricCache.Store(key, data)
		}
	}

	//c.Logger.Debugf("key: %v", kv["name"])

	var sub *sync.Map
	subi, _ := c.MetricsSubscriber.LoadOrStore(key, &sync.Map{})
	sub = subi.(*sync.Map)

	bts, _ := json.Marshal(data)
	str := string(bts)

	sub.Range(func(k, v interface{}) bool {
		mch := v.(chan string)
		mch <- str
		return true
	})

	c.MetricsSubscriberTotal.Range(func(k, v interface{}) bool {
		mch := v.(chan string)
		mch <- str
		return true
	})
}
